"use server";
import { getPasswordRestTokenByToken } from "@/data/password-reset-token";
import * as z from "zod";
import { db } from "@/lib/db";
import { NewPasswordSchema } from "@/schemas";
import { Code } from "@/common/code";
import { getUserByEmail } from "@/data/user";
import { hash } from "bcryptjs";
export const resetPassword = async (
  token: string,
  values: z.infer<typeof NewPasswordSchema>
) => {
  const validateFilelds = NewPasswordSchema.safeParse(values);
  if (!validateFilelds) {
    return {
      code: Code.INVALID_FIELDS,
      data: "Invalid fields",
      message: "Invalid fields",
    };
  }
  const resetToken = await getPasswordRestTokenByToken(token);
  if (!resetToken) {
    return {
      code: Code.NOT_FOUND,
      data: "TOKEN NOT FOUND",
      message: "TOKEN NOT FOUND",
    };
  }
  const isExpire = new Date().getTime() > resetToken.expires.getTime();
  if (isExpire) {
    return {
      code: Code.EXPIRE,
      data: "email is expire",
      message: "email is expire",
    };
  }
  const user = await getUserByEmail(resetToken.email);
  if (!user) {
    return {
      code: Code.NOT_FOUND,
      data: "user not found",
      message: "user not found",
    };
  }
  // 更新密码
  const { password } = validateFilelds.data!;
  const newPassword = await hash(password, 10);
  await db.user.update({
    where: {
      id: user.id,
    },
    data: {
      password: newPassword,
    },
  });
  return {
    code: Code.SUCCESS,
  };
};
